﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Spire.Pdf;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZXing;

namespace WindowsFormsApp
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            bindCbox();
        }

        private void button1_Click(object sender, EventArgs e)
        {            
            ServicePointManager.DefaultConnectionLimit = 500;
            this.progressbar.Visible = true;
            Thread td = new Thread(StartProccess);
            td.Start();
            td.IsBackground = true;
        }

        private void StartProccess()
        {
            try
            {
                var value = this.ticketTemplate.SelectedValue;
                string text = ticketTemplate.Text;
                if (ItemListBox.Items.Count <= 0)
                {
                    MessageBox.Show("请选择需要处理的电子票");
                    return;
                }
                if (string.IsNullOrEmpty(savePath.Text))
                {
                    MessageBox.Show("请选择保存的位置");
                    return;
                }
                int index = 0;
                var startTime = DateTime.Now;
                int success = 0;
                int count = ItemListBox.Items.Count;
                List<TicketEntity> tickets = new List<TicketEntity>();
                foreach (var item in ItemListBox.Items)
                {
                    string fileName = Path.GetFileName(item.ToString());
                    List<TicketEntity> list = getTicketEntityByPath(item.ToString(), Convert.ToInt32(value));
                    tickets.AddRange(list);
                    success += 1;
                    lbMsg.Text = string.Format("{0}提取成功", item.ToString());
                    progressbar.Value = success;
                    string strText = string.Format("当前进度:{0}/{1}", success, count);
                    Font font = new Font("微软雅黑", (float)12, FontStyle.Italic);
                    PointF pointF = new PointF(this.progressbar.Width / 2 - 10, this.progressbar.Height / 2 - 10);
                    progressbar.CreateGraphics().DrawString(strText, font, Brushes.Black, pointF);
                }

                tickets.ForEach(p =>
                {
                    index += 1;
                    p.SerialNumber = index.ToString();
                });

                DataTable dt = ListHelper.ListToDt<TicketEntity>(tickets);
                var time = DateTime.Now.ToString("HHmmssfff");
                lbMsg.Text = "正在生成Excel...";
                ExcelHelper.TableToExcel(dt, $"{savePath.Text.Replace("保存位置:", string.Empty)}\\{ticketTemplate.Text}-{time}.xlsx");
                lbMsg.Text = "生成Excel成功";
                var endTime = DateTime.Now;
                TimeSpan ts = endTime.Subtract(startTime);
                var seconds = ts.TotalSeconds;


                MessageBox.Show($"生成完成,共计{tickets.Count}条记录,总耗时{seconds}秒");
            }
            catch(Exception ex)
            {
                MessageBox.Show("抱歉,程序出现了异常,请联系技术支持...");
            }
            
        }

        private TicketEntity ShibieData(string fileName)
        {            
            string data = GetPdfContext(fileName).Replace("            ", string.Empty);
            string strArry = Regex.Split(data, "IMPORTANT NOTES", RegexOptions.IgnoreCase)[0].Trim();
            string[] arry = Regex.Split(strArry, "\r\n", RegexOptions.IgnoreCase);

            TicketEntity entity = new TicketEntity();
            entity.OrderNumber = arry[3].Replace("Order Number.:", string.Empty).Trim();
            entity.TicketNumber = arry[6].Replace("Redemption Code", string.Empty).Trim();
            entity.ScenicName = arry[5].Replace("Deal Name", string.Empty).Trim();
            entity.SupplierName = arry[0].Trim();
            entity.FileName = System.IO.Path.GetFileName(fileName);
            entity.PageIndex = 1;
            return entity;
        }





        private static string GetPdfContext(string path)
        {
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile(path);
            //获取第一页
            PdfPageBase page = pdf.Pages[0];
            //从第一页的指定矩形区域内提取文本
            string text = page.ExtractText();
            text = text.Replace("Evaluation Warning : The document was created with Spire.PDF for .NET.", string.Empty);
            return text;
        }

        public static TicketReadConfig currentConfig;

        private void button3_Click(object sender, EventArgs e)
        {            
            string path = @"D:\workspace\TicketApp\WindowsFormsApp\pdf\test_no_del\11.新加坡夜间动物园-兑换版.pdf";
            TicketEntity ticketEntity = new TicketEntity();
            string content = GetPdfContext(path).Trim();
            string strArry = Regex.Split(content, "Note:", RegexOptions.IgnoreCase)[0].Trim();
            string[] arry = Regex.Split(strArry, "\r\n", RegexOptions.IgnoreCase);  
            var scenicData = arry[12].Trim();
            ticketEntity.ScenicName = Regex.Split(scenicData, "    ", RegexOptions.IgnoreCase)[1].Replace("(Adult)", string.Empty).Replace("(Child)", string.Empty);
            ticketEntity.OrderNumber = Regex.Split(arry[7].Trim(), "Name:", RegexOptions.IgnoreCase)[0].Trim().Replace("Collection Note No:",string.Empty).Trim();
            ticketEntity.SupplierName = Regex.Split(arry[7].Trim(), "Name:", RegexOptions.IgnoreCase)[1].Trim();
            ticketEntity.TicketNumber = arry[1].Trim();
            ticketEntity.Type = scenicData.ToUpper().Contains("(ADULT)") ? "ADULT" : "CHILD";
            ticketEntity.ValidityDate = arry[arry.Length-1].Trim().Replace("Validity Period:",string.Empty);

        }

        public List<TicketEntity> getTicketEntityByPath(string path,int index)
        {
            List<TicketEntity> list = new List<TicketEntity>();

            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile(path);

           

            for (int i = 0; i < doc.Pages.Count; i++)
            {
                var ticketEntity = new TicketEntity();

                ticketEntity.FileName = path;
                ticketEntity.PageIndex = i + 1;

                // 实例化一个Spire.Pdf.PdfPageBase对象
                PdfPageBase page = doc.Pages[i];

                #region 图片处理
                //先要判断当前票种要不要识别条形码
                if (currentConfig.NeedReadImages)
                {
                    // 获取所有pages里面的图片
                    Image[] images = page.ExtractImages();
                    if (images != null && images.Length > 0)
                    {
                        var barCodeIndex = currentConfig.ImageIndex;
                        var barCodeImage = images[barCodeIndex];

                        ticketEntity.TicketNumber = getCodyByImg((Bitmap)barCodeImage);

                        #region 识别时不用保存 此用于看是第几张  另: 调试时生成到Debug目录
                        //for (int k = 0; k < images.Length; k++)
                        //{
                        //    Image image = images[k];
                        //    image.Save("image_" + (k + 1).ToString() + ".png", System.Drawing.Imaging.ImageFormat.Png);
                        //}
                        #endregion


                    }
                }

                #endregion

                #region 文本处理
                string text = page.ExtractText();
                text = text.Replace("Evaluation Warning : The document was created with Spire.PDF for .NET.", string.Empty);
                string data = text.Replace("            ", string.Empty);
                HandleEntity(index, data, ticketEntity);
                ticketEntity.FileName = Path.GetFileName(path);

                #endregion

                list.Add(ticketEntity);

            }
            return list;
        }

        private void HandleEntity(int index,string content, TicketEntity ticketEntity)
        {
            if (index == 1)
            {
                string strArry = Regex.Split(content, "IMPORTANT NOTES", RegexOptions.IgnoreCase)[0].Trim();
                string[] arry = Regex.Split(strArry, "\r\n", RegexOptions.IgnoreCase);

                ticketEntity.OrderNumber = arry[3].Replace("Order Number.:", string.Empty).Trim();
                ticketEntity.TicketNumber = arry[6].Replace("Redemption Code", string.Empty).Trim();
                ticketEntity.ScenicName = arry[5].Replace("Deal Name", string.Empty).Trim();
                ticketEntity.SupplierName = arry[0].Trim();
            }
            else if (index == 2)
            {
                string[] arry = Regex.Split(content.Trim(), "\r\n", RegexOptions.IgnoreCase);
                ticketEntity.OrderNumber = arry[5].Replace("Order Number:", string.Empty).Trim();
                ticketEntity.SupplierName = arry[0].Trim();
                ticketEntity.TicketNumber = arry[9].Replace("Redemption Code:", string.Empty).Trim();
                ticketEntity.ScenicName = arry[8].Replace("Deal Name:", string.Empty).Trim();
            }
            else if (index == 3)
            {
                string strArry = Regex.Split(content, "Terms and conditions", RegexOptions.IgnoreCase)[0].Trim();
                string strReference = Regex.Split(content, "Terms and conditions", RegexOptions.IgnoreCase)[1].Trim();
                var referenceArry = Regex.Split(strReference, "\r\n", RegexOptions.IgnoreCase).ToList();
                int referenceIndex = referenceArry.FindIndex(p => p.Trim().StartsWith("WRS Reference:"));
                var referenceData = referenceArry[referenceIndex].Replace("WRS Reference:",string.Empty).Trim();
                string[] arry = Regex.Split(strArry, "\r\n", RegexOptions.IgnoreCase);                
                var data = arry[3].Trim().Replace("Collection Note No:", string.Empty);
                ticketEntity.WRSReference = referenceData;
                ticketEntity.OrderNumber = Regex.Split(data, "Name:", RegexOptions.IgnoreCase)[0].Trim();
                ticketEntity.SupplierName = Regex.Split(data, "Name:", RegexOptions.IgnoreCase)[1].Trim();
                int collectIndex = arry.ToList().FindIndex(p => p.Contains("Quantity")) + 1;
                var drry = Regex.Split(arry[collectIndex].Trim(), "    ", RegexOptions.IgnoreCase)[1].Trim();
                int typeIndex = 0;
                if (drry.IndexOf("Adult") > 0)
                {
                    typeIndex = drry.IndexOf("Adult") - 1;
                    ticketEntity.Type = "Adult";
                }
                else if (drry.IndexOf("Child") > 0)
                {
                    typeIndex = drry.IndexOf("Child") - 1;
                    ticketEntity.Type = "Child";
                }
                ticketEntity.ScenicName = drry.Substring(0,typeIndex).Trim();
                ticketEntity.ValidityDate = arry[arry.Length - 1].Replace("Validity Period:", string.Empty).Trim();
            }
            else if (index == 4)
            {
                string strArry = Regex.Split(content, "Note:", RegexOptions.IgnoreCase)[0].Trim();
                string strReference = Regex.Split(content, "Note:", RegexOptions.IgnoreCase)[1].Trim();
                var referenceArry = Regex.Split(strReference, "\r\n", RegexOptions.IgnoreCase).ToList();
                int referenceIndex = referenceArry.FindIndex(p => p.Trim().StartsWith("WRS Reference:"));
                var referenceData = referenceArry[referenceIndex].Replace("WRS Reference:", string.Empty).Trim();
                ticketEntity.WRSReference = referenceData;
                string[] arry = Regex.Split(strArry, "\r\n", RegexOptions.IgnoreCase);
                ticketEntity.TicketNumber = arry[1].Trim();                
                int noteNoIndex = arry.ToList().FindIndex(p => p.Contains("Collection Note No"));
                var data = arry[noteNoIndex].Trim().Replace("Collection Note No:", string.Empty);
                ticketEntity.OrderNumber = Regex.Split(data, "Name:", RegexOptions.IgnoreCase)[0].Trim();
                ticketEntity.SupplierName = Regex.Split(data, "Name:", RegexOptions.IgnoreCase)[1].Trim();
                int quantityIndex = arry.ToList().FindIndex(p => p.Contains("Quantity"));
                var drry = Regex.Split(arry[quantityIndex+1].Trim(), "    ", RegexOptions.IgnoreCase)[1].Trim();
                int typeIndex = 0;
                if (drry.IndexOf("Adult") > 0)
                {
                    typeIndex = drry.IndexOf("Adult") - 1;
                    ticketEntity.Type = "Adult";
                }
                else if (drry.IndexOf("Child") > 0)
                {
                    typeIndex = drry.IndexOf("Child") - 1;
                    ticketEntity.Type = "Child";
                }
                ticketEntity.ScenicName = drry.Substring(0, typeIndex).Trim();
                ticketEntity.ValidityDate = arry[quantityIndex+2].Trim().Replace("Validity Period:", string.Empty);
            }
            else if (index == 5)
            {
                string strArry = Regex.Split(content, "HOW TO USE THIS E-TICKET", RegexOptions.IgnoreCase)[0].Trim();
                string[] arry = Regex.Split(strArry, "\r\n", RegexOptions.IgnoreCase);
                ticketEntity.ScenicName = Regex.Split(arry[0], "Customer :", RegexOptions.IgnoreCase)[0].Trim();
                ticketEntity.SupplierName = Regex.Split(arry[0], "Customer :", RegexOptions.IgnoreCase)[1].Trim().Replace("Customer :", string.Empty).Trim();
                ticketEntity.ValidityDate = arry[2].Trim().Replace("Valid from", string.Empty).Trim();
                ticketEntity.OrderNumber = Regex.Split(arry[1], "Order # :", RegexOptions.IgnoreCase)[1].Trim();
                ticketEntity.Type = Regex.Split(arry[1], "Order # :", RegexOptions.IgnoreCase)[0].Trim();
                if (ticketEntity.Type.ToUpper().Contains("ADULT"))
                {
                    ticketEntity.Type = "ADULT";
                }
                else if (ticketEntity.Type.ToUpper().Contains("CHILD"))
                {
                    ticketEntity.Type = "CHILD";
                }
            }
            else if (index == 6)
            {
                string strArry = Regex.Split(content, "How to use this ticket", RegexOptions.IgnoreCase)[0].Trim();
                string[] arry = Regex.Split(strArry, "\r\n", RegexOptions.IgnoreCase);
                ticketEntity.ValidityDate = arry[4].Trim().Replace("Validity Period", string.Empty).Trim();
                ticketEntity.OrderNumber = arry[3].Trim().Replace("Transaction ID", string.Empty).Trim();
                ticketEntity.TicketNumber = arry[11].Trim();
                ticketEntity.Type = Regex.Split(arry[7].Trim().Replace("Ticket type", string.Empty).Trim(), "   ", RegexOptions.IgnoreCase)[0].Trim();
                var list = Regex.Split(arry[6].Trim(), "   ", RegexOptions.IgnoreCase);
                ticketEntity.SupplierName = list[list.Length - 1].Trim();
                ticketEntity.ScenicName = arry[0].Trim();
            }
            else if (index == 7)
            {
                string strArry = Regex.Split(content, "Terms & Conditions", RegexOptions.IgnoreCase)[0].Trim();
                string[] arry = Regex.Split(strArry, "\r\n", RegexOptions.IgnoreCase);
                ticketEntity.ValidityDate = arry[4].Trim().Replace("Valid till:", string.Empty);
                ticketEntity.OrderNumber = arry[6].Trim().Replace("Issued on:", string.Empty).Trim();
                ticketEntity.TicketNumber = arry[5].Trim();
                ticketEntity.Type = arry[3].Trim().Contains("(A)") ? "ADULT" : "CHILD";
                ticketEntity.ScenicName = arry[1].Trim();
            }
            else if (index == 8)
            {
                string[] arry = Regex.Split(content, "\r\n", RegexOptions.IgnoreCase);
                int typeIndex = arry.ToList().FindIndex(p => p.Contains("Age Group"));
                if (typeIndex > 0)
                {
                    ticketEntity.ScenicName = Regex.Split(arry[3].Trim(), "   ", RegexOptions.IgnoreCase)[0];
                    string data = arry[9].Trim().Replace("Ticket Code ：", string.Empty).Trim();
                    var list = Regex.Split(data, "    ", RegexOptions.IgnoreCase);
                    ticketEntity.OrderNumber = list[0].Trim();
                    ticketEntity.TicketNumber = list[list.Length - 1].Trim();
                    ticketEntity.Type = arry[typeIndex].Trim().Contains("Adult") ? "Adult" : "Child";
                    var d = arry.ToList().FindAll(p => p.Trim().StartsWith("Travel Company")).FirstOrDefault().Replace("Travel Company：", string.Empty);
                    ticketEntity.SupplierName = Regex.Split(d.Trim(), "   ", RegexOptions.IgnoreCase)[0].Trim();
                    ticketEntity.ValidityDate = Regex.Split(arry[19].Trim(), "Valid for", RegexOptions.IgnoreCase)[0].Trim();
                }
                else
                {
                    ticketEntity.ScenicName = Regex.Split(arry[3].Trim(), "   ", RegexOptions.IgnoreCase)[0];
                    int dataIndex = arry.ToList().FindIndex(p => p.Contains("Ticket Code"));
                    string data = arry[dataIndex].Trim().Replace("Ticket Code ：", string.Empty).Replace("Ticket Price", string.Empty).Trim();
                    var list = Regex.Split(data, "  ", RegexOptions.IgnoreCase);
                    ticketEntity.OrderNumber = list[0].Trim();
                    ticketEntity.TicketNumber = list[list.Length - 1].Trim();
                    typeIndex = arry.ToList().FindIndex(p => p.Contains("年龄区分"));
                    ticketEntity.Type = arry[typeIndex].Trim().Contains("Adult") ? "Adult" : "Child";
                    var d = arry.ToList().FindAll(p => p.Trim().StartsWith("旅行社：")).FirstOrDefault().Replace("旅行社：", string.Empty);
                    ticketEntity.SupplierName = Regex.Split(d.Trim(), "   ", RegexOptions.IgnoreCase)[0].Trim();
                    ticketEntity.ValidityDate = Regex.Split(arry[18].Trim(), "期间", RegexOptions.IgnoreCase)[0].Trim();
                }
            }            
            else if (index == 9)
            {
                string strArry = Regex.Split(content, "How to use This Voucher", RegexOptions.IgnoreCase)[0].Trim();
                string[] arry = Regex.Split(strArry, "\r\n", RegexOptions.IgnoreCase);
                ticketEntity.ScenicName = Regex.Split(arry[3].Trim(), "   ", RegexOptions.IgnoreCase)[0];                
                int orderIndex = arry.ToList().FindIndex(p => p.Contains("Order No. / Conf. No:"));
                ticketEntity.OrderNumber = Regex.Split(arry[orderIndex].Trim(), "Order No.", RegexOptions.IgnoreCase)[1].Replace("/ Conf. No:", string.Empty).Replace("/", string.Empty).Trim();
                ticketEntity.TicketNumber = arry[0].Trim();
                int typeIndex = arry.ToList().FindIndex(p => p.Contains("Ticket:"));
                ticketEntity.Type = arry[typeIndex].Trim().ToUpper().Contains("ADULT") ? "ADULT" : "CHILD";
                ticketEntity.SupplierName = Regex.Split(arry[4].Trim(), "Customer:", RegexOptions.IgnoreCase)[1].Trim();
                ticketEntity.ValidityDate = Regex.Split(arry[orderIndex].Trim(), "Order No", RegexOptions.IgnoreCase)[0].Trim().Replace("Valid from:", string.Empty);
            }
            else if (index == 10)
            {
                //待加   F:\TicketApp\WindowsFormsApp\pdf 0415 下有三张票 皆测试一下得
                string strArry = Regex.Split(content, "How to use This Voucher", RegexOptions.IgnoreCase)[0].Trim();
                string[] arry = Regex.Split(strArry, "\r\n", RegexOptions.IgnoreCase);
                string orderNumber_content = arry[1].Replace("Purchased Date:", string.Empty).Replace("Ticket Validity:", string.Empty).Trim().Replace("  "," ");
                string orderTicket_content = arry[2].Replace("Purchased By:", string.Empty).Replace("Confirmation Code:", string.Empty).Trim().Replace("  ", " ");
                string[] orderNumber_list = Regex.Split(orderNumber_content, "     ", RegexOptions.IgnoreCase);
                string[] ticketNumber_list = Regex.Split(orderTicket_content, "     ", RegexOptions.IgnoreCase);
                ticketEntity.OrderNumber = orderNumber_list[0];
                ticketEntity.ValidityDate = orderNumber_list[1];
                ticketEntity.SupplierName = ticketNumber_list[0];
                ticketEntity.TicketNumber = ticketNumber_list[1];
                ticketEntity.ScenicName = arry[4].Trim();
                ticketEntity.Type = Regex.Split(arry[3].Trim(), "Ticket:", RegexOptions.IgnoreCase)[1].Split('(')[0];                
            }
            else if (index == 11)
            {
                string strArry = Regex.Split(content, "HOW TO USE THIS E-TICKET", RegexOptions.IgnoreCase)[0].Trim();
                string[] arry = Regex.Split(strArry, "\r\n", RegexOptions.IgnoreCase);
                ticketEntity.OrderNumber = arry[2].Replace("Order # :", "").Trim();
                string[] ticketNumber_list = Regex.Split(arry[0], "Customer : ", RegexOptions.IgnoreCase);
                ticketEntity.SupplierName = ticketNumber_list[1].Trim();
                ticketEntity.ScenicName = ticketNumber_list[0].Trim();
                ticketEntity.Type = arry[1].ToUpper().Contains("ADULT") ? "ADULT" : "CHILD";
                ticketEntity.ValidityDate = Regex.Split(arry[3], "to", RegexOptions.IgnoreCase)[1].Trim();                
            }
            else if (index == 12)
            {
                string strArry = Regex.Split(content, "HOW TO USE THIS E-TICKET", RegexOptions.IgnoreCase)[0].Trim();
                string[] arry = Regex.Split(strArry, "\r\n", RegexOptions.IgnoreCase);
                ticketEntity.OrderNumber = arry[2].Replace("Order # :", "").Trim();
                string[] ticketNumber_list = Regex.Split(arry[0], "Customer : ", RegexOptions.IgnoreCase);
                ticketEntity.SupplierName = ticketNumber_list[1].Trim();
                ticketEntity.ScenicName = ticketNumber_list[0].Trim();
                ticketEntity.Type = arry[1].ToUpper().Contains("ADULT") ? "ADULT" : "CHILD";
                ticketEntity.ValidityDate = Regex.Split(arry[3], "to", RegexOptions.IgnoreCase)[1].Trim();
            }
            else if (index == 13)
            {
                string strArry = Regex.Split(content, "TERMS AND CONDITIONS:", RegexOptions.IgnoreCase)[0].Trim();
                string[] arry = Regex.Split(strArry, "\r\n", RegexOptions.IgnoreCase);
                ticketEntity.TicketNumber = Regex.Split(arry[5], "Confirmation Code:", RegexOptions.IgnoreCase)[1].Trim();
                ticketEntity.SupplierName = Regex.Split(arry[5], "Confirmation Code:", RegexOptions.IgnoreCase)[0].Trim().Replace("Purchased By:",string.Empty).Trim();
                ticketEntity.ValidityDate = Regex.Split(arry[4], "Ticket Validity:", RegexOptions.IgnoreCase)[1].Trim();
                ticketEntity.Type = arry[6].ToUpper().Contains("ADULT") ? "ADULT" : "CHILD";
                ticketEntity.ScenicName = Regex.Split(arry[6], "Ticket", RegexOptions.IgnoreCase)[0].Trim();
            }
            else if (index == 14)
            {
                string strArry = Regex.Split(content, "THIS IS YOUR E-TICKET:", RegexOptions.IgnoreCase)[0].Trim();
                string[] arry = Regex.Split(strArry, "\r\n", RegexOptions.IgnoreCase);
                ticketEntity.OrderNumber = Regex.Split(arry[3], "Partners Order # :")[1];
                ticketEntity.ValidityDate = Regex.Split(arry[3], "Partners Order # :")[0].Trim().Replace("VALID FROM ", "");
                ticketEntity.Type = Regex.Split(arry[2].ToUpper(), " TAB")[0].Split(' ').Last<String>();

                ticketEntity.ScenicName = "S.E.A. Aquarium™";
                ticketEntity.SupplierName = Regex.Split(arry[1], "Customer :") + Regex.Split(arry[2], "  ").Last<String>();
            }

            ticketEntity.ValidityDate = GetValidityDate(ticketEntity.ValidityDate, index);
        }

        

        /// <summary>
        /// 日期格式化
        /// </summary>
        /// <param name="validityDate"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        private static string GetValidityDate(string validityDate,int index)
        {
            string resultDate = string.Empty;
            if (string.IsNullOrEmpty(validityDate))
            {
                return resultDate;
            }
            Dictionary<string, string> dicList = new Dictionary<string, string>();
            dicList.Add("JAN", "01");
            dicList.Add("FEB", "02");
            dicList.Add("MAR", "03");
            dicList.Add("APR", "04");
            dicList.Add("MAY", "05");
            dicList.Add("JUN", "06");
            dicList.Add("JUL", "07");
            dicList.Add("AUG", "08");
            dicList.Add("SEP", "09");
            dicList.Add("OCT", "10");
            dicList.Add("NOV", "11");
            dicList.Add("DEC", "12");
            switch (index)
            {
                case 1:
                case 2:
                    //{
                    //    var list = validityDate.Split('-');
                    //    resultDate = $"{list[2]}/{dicList[list[1]]}/{list[0]}";
                    //}                    
                    break;
                case 3:
                case 4:                
                    {
                        //30 Nov 2019 - 30 Mar 2020
                        var list = validityDate.Split('-')[1].Trim().Split(' ');
                        resultDate = $"{list[2]}/{dicList[list[1].ToUpper()]}/{list[0]}";
                    }                    
                    break;
                case 5:
                    {
                        //30 DEC 2019 to 28 APR 2020
                        var list = Regex.Split(validityDate,"to", RegexOptions.IgnoreCase)[1].Trim().Split(' ');
                        resultDate = $"{list[2]}/{dicList[list[1].ToUpper()]}/{list[0]}";
                    }
                    break;
                case 6:                
                    {
                        //17 JAN 2020 – 14 JUL 2020
                        var list = validityDate.Split('–')[1].Trim().Split(' ');
                        resultDate = $"{list[2]}/{dicList[list[1].ToUpper()]}/{list[0]}";
                    }
                    break;
                case 7:
                    {
                        DateTime dt = DateTime.ParseExact(validityDate.Trim(), "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
                        resultDate = dt.ToString("yyyy/MM/dd");
                    }
                    break;
                case 8:
                    {
                        validityDate = validityDate.Split('～')[1].Trim();
                        DateTime dt = DateTime.ParseExact(validityDate, "yyyy.MM.dd", System.Globalization.CultureInfo.CurrentCulture);
                        resultDate = dt.ToString("yyyy/MM/dd");
                    }
                    break;
                case 9:
                    {
                        //03/12/2019 thru 03/06/2020
                        validityDate = Regex.Split(validityDate, "thru", RegexOptions.IgnoreCase)[1].Trim();
                        DateTime dt = DateTime.ParseExact(validityDate, "dd/MM/yyyy", System.Globalization.CultureInfo.CurrentCulture);
                        resultDate = dt.ToString("yyyy/MM/dd");
                    }
                    break;
                case 10:
                case 13:
                    {
                        //04 July 2020
                        var list = Regex.Split(validityDate.Trim(), " ", RegexOptions.IgnoreCase);
                        resultDate = $"{list[2]}/{dicList[list[1].Substring(0,3).ToUpper()]}/{list[0]}";
                    }
                    break;
                case 11:
                case 12:
                    var year = validityDate.Substring(validityDate.Length - 4);
                    var month = validityDate.Substring(validityDate.Length - 7, 3);
                    var day = validityDate.Substring(0,validityDate.Length - 7);
                    resultDate = $"{year}/{dicList[month.ToUpper()]}/{day}";
                    break;
                case 14:
                    {
                        //03/12/2019 THRU 03/06/2020
                        var validityDateStart = Regex.Split(validityDate, " THRU ", RegexOptions.IgnoreCase)[0].Trim();
                        var validityDateEnd =   Regex.Split(validityDate, " THRU ", RegexOptions.IgnoreCase)[1].Trim();


                        DateTime dt_start = DateTime.ParseExact(validityDateStart, "dd/MM/yyyy", System.Globalization.CultureInfo.CurrentCulture);
                        DateTime dt_end = DateTime.ParseExact(validityDateEnd, "dd/MM/yyyy", System.Globalization.CultureInfo.CurrentCulture);
                        resultDate = dt_start.ToString("yyyy/MM/dd")+ "-" + dt_end.ToString("yyyy/MM/dd");
                    }
                    break;
                default:
                    break;
            }
            return resultDate;
        }




        private void button4_Click(object sender, EventArgs e)
        {
            getCodyByImg("");
        }

        public static void getCodyByImg(string path)
        {
            if (String.IsNullOrWhiteSpace(path))
            {
                path = "F:/TicketApp/WindowsFormsApp/bin/Debug/image_3.png";
            }
            // create a barcode reader instance
            IBarcodeReader reader = new BarcodeReader();
            // load a bitmap
            var barcodeBitmap = (Bitmap)Image.FromFile(path);
            // detect and decode the barcode inside the bitmap
            var result = reader.Decode(barcodeBitmap);
            // do something with the result
            if (result != null)
            {
                MessageBox.Show(result.BarcodeFormat.ToString());
                MessageBox.Show(result.Text);
            }
        }

        public static string getCodyByImg(Bitmap bitmap)
        {
            // create a barcode reader instance
            IBarcodeReader reader = new BarcodeReader();
            // load a bitmap
            var barcodeBitmap = bitmap;
            // detect and decode the barcode inside the bitmap
            var result = reader.Decode(barcodeBitmap);
            // do something with the result
            if (result != null)
            {
                //MessageBox.Show(result.BarcodeFormat.ToString());
                //MessageBox.Show(result.Text);
                return result.Text;
            }
            else
            {
                return "";
            }

        }

        /// <summary>
        /// 选择文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void choice_Click(object sender, EventArgs e)
        {            
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = true;
            fileDialog.Filter = "(*.pdf)|*.PDF";
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                string[] files = fileDialog.FileNames;                
                foreach (string f in files)
                {
                    ItemListBox.Items.Add(f);
                }
                ChangeForBtnCanUse();
                this.progressbar.Maximum = files.Length;
            }            
        }

        private void bindCbox()
        {
            string strPath = System.IO.Directory.GetCurrentDirectory();
            string folder = $"{strPath}\\pdf\\config.json";
            //read the json 
            var sourceContent = File.ReadAllText(folder,Encoding.Default);
            List<TicketReadConfig> list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<TicketReadConfig>>(sourceContent);
            ticketTemplate.DataSource = list;
            ticketTemplate.ValueMember = "TicketID";
            ticketTemplate.DisplayMember = "TicketName";
        }

        /// <summary>
        /// 保存到
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveTo_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                savePath.Text = "保存位置:" + dialog.SelectedPath;

                ChangeForBtnCanUse();



            }
        }

        private void ticketTemplate_SelectedIndexChanged(object sender, EventArgs e)
        {
            string strPath = System.IO.Directory.GetCurrentDirectory();
            string folder = $"{strPath}\\pdf\\config.json";
            //read the json 
            var sourceContent = File.ReadAllText(folder, Encoding.Default);
            List<TicketReadConfig> list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<TicketReadConfig>>(sourceContent);
            try
            {                
                var value = this.ticketTemplate.SelectedValue;
                currentConfig = list.Find(p => p.TicketID == Convert.ToInt32(value));
            }
            catch (Exception ex)
            {
                currentConfig = list.Find(p => p.TicketID == 1);
            }            
        }

        private void button2_Click(object sender, EventArgs e)
        {

            if (!String.IsNullOrWhiteSpace(savePath.Text))
            {
                string v_OpenFolderPath = savePath.Text.Replace("保存位置:", "");
                System.Diagnostics.Process.Start("explorer.exe", v_OpenFolderPath);

            }
           
        }

        private void ChangeForBtnCanUse()
        {
            if (ItemListBox.Items.Count > 0 && !string.IsNullOrEmpty(savePath.Text))
            {
                button1.Enabled = true;
            }
            else
            {
                button1.Enabled = false;
            }

           
            if (!string.IsNullOrWhiteSpace(savePath.Text))
            {
                button2.Enabled = true;
            }
            else
            {
                button2.Enabled = false;
            }

            if (ItemListBox.Items.Count > 0)
            {
                label2.Text = $"共选中{ItemListBox.Items.Count}个文件";
            }
            else
            {
                label2.Text = "";
            }



        }

        private void Main_Load(object sender, EventArgs e)
        {
            linkLabel1.Links.Add(0,4, "https://gitee.com/xueyejinghong");
        }

        private void clearFile_Click(object sender, EventArgs e)
        {
            ItemListBox.Items.Clear();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            linkLabel1.Links[linkLabel1.Links.IndexOf(e.Link)].Visited = true;
            string targetUrl = e.Link.LinkData as string;
            if (string.IsNullOrEmpty(targetUrl))
                MessageBox.Show("没有链接地址！");
            else
                System.Diagnostics.Process.Start(targetUrl);
        }
    }


}
